<?php
/*
 * 文章控制器
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
use shu\Tree;
class Article extends Comm
{
    public function index($sid = 0, $p = 1,$pid=0)
    {
        $article = db('article');
        $pagesize = 20;
        $prefix = config('database.prefix');
        $sid = isset($_GET['sid']) ? $_GET['sid'] : '';
        $keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
        $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
        if($pid){
			$map1['id']=$pid;
		    $map = " concat(',',path,',') like '%,$pid,%'  ";
			$data = db('category')->where($map1)->whereOr($map)->select();
			foreach($data as $k=>$v){
				$class[]=$v['id'];  //获取所有分类ID
			}
            $path = implode(',',$class);
            $mapp['sid'] = array ('in',$class);
            //$where = "sid in(".$path.")";
			$where['sid'] = array ('in',$class);
        }else{
            $where = '1 = 1 ';
        }
        
        if ($sid) {
            $sids_array = category_get_sons($sid);
            $sids = implode(',',$sids_array);
            //$where .= "and {$prefix}article.sid in ($sids) ";
			$where['sid'] = ['in',$sids];
        }
        if ($keyword) {
            //$where .= "and {$prefix}article.title like '%{$keyword}%' ";
			$where['title'] = ['like','%'.$keyword.'%'];
        }
        //默认按照时间降序
        $orderby = "o desc, t desc,aid desc";
        if ($order == "asc") {

            $orderby = "o desc, t asc ,aid asc";
        }
        //获取栏目分类
		//print_r($where);die;	
        $category = db('category')->where($map1)->whereOr($map)->order('o asc')->select();
		//echo $sid;die;
        $tree = new Tree($category);
		
        $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
        $category = $tree->get_tree(0, $str, $sid);
        $this->assign('category', $category);//导航

        $count = $article->where($where)->count();
		$list =$article->alias('a')->field(['a.*','w.name'])->where($where)->order($orderby)->join('qw_category w','w.id = a.sid')->paginate($pagesize,$count,['query' => array('sid'=>$sid,'keyword'=>$keyword,'order'=>$order)]);
		
		//->paginate($pagesize,$count)   order($orderby)
		//echo $list;die; 
		
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
		
        return $this->fetch();
    }

    public function add($pid=0)
    {
		$map1['id']=$pid;
		$map = "  concat(',',path,',') like '%,$pid,%'  ";
        $category = db('category')->where($map1)->whereOr($map)->field('id,pid,name')->order('o asc')->select();
		//echo M('category')->getlastsql();die;
        $tree = new Tree($category);
        $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
        $category = $tree->get_tree(0, $str, 0);
        $this->assign('category', $category);//导航
        $this->assign('pid', $pid);
        $ttt = time();
        $this->assign('ttt', $ttt);
        return $this->fetch('form');
    }

    public function edit($aid,$pid=0)
    {

        $aid = intval($aid);
        $article = db('article')->where('aid=' . $aid)->find();
        if ($article) {
			$map1['id']=$pid;
			$map = "  concat(',',path,',') like '%,$pid,%'  ";
            $category = db('category')->where($map1)->whereOr($map)->field('id,pid,name')->order('o asc')->select();
            $tree = new Tree($category);
            $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
            $category = $tree->get_tree(0, $str, $article['sid']);
            $this->assign('category', $category);//导航
            $this->assign('article', $article);
            $this->assign('pid', $pid);
        } else {
            $this->error('参数错误！');
        }
        return $this->fetch('form');
    }	
	
	
    public function del($pid=null)
    {
		$ids = input('param.');
        if ($ids) {
            if (is_array($ids)) {
				if (request()->isGet()){
					$map['aid'] = $ids= $ids['ids'];
				}else{
					$ids = implode(',', $ids['ids']);
					$map['aid'] = array('in', $ids);	
				}
				//删除文件
        		$data = db('article')->where($map)->select();
				foreach($data as $k=>$v){
					if($v['thumbnail']){
						$Imge = explode('|', $v['thumbnail']);
						foreach($Imge as $kk=>$vv){
							if(file_exists('.'.$vv)){
								unlink('.'.$vv); 
							} 
						}
					}
				}
            } else {
                $this->error('参数错误！');
            }
            if (db('article')->where($map)->delete()) {
                addlog('删除文章，AID：' . $ids);
                //$this->success('恭喜，文章删除成功！',url('index',array('pid'=>$pid)));
				return json(array('code' => 200, 'msg' => '恭喜，文章删除成功！'));	
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }
    }
	
	
    public function update($act = null,$aid = 0,$pid=0,$sid=0)
    {
        if ($act == 'order') {
            $aid = input('post.aid', 0, 'intval');
            if (!$aid) {
                return json(array('code' => 0, 'msg' => '失败'));
            }
            $o = input('post.o', 0, 'intval');
            db('article')->data(array('o' => $o))->where('aid',$aid)->update();
            addlog('分类修改排序，ID：' . $aid);
            return json(array('code' => 200, 'msg' => '排序成功'));
   		 }
		 
		$aid = intval($aid);
        $data['sid'] = isset($_POST['sid']) ? intval($_POST['sid']) : 0;
        $data['title'] = isset($_POST['title']) ? $_POST['title'] : false;
        $data['seotitle'] = isset($_POST['seotitle']) ? $_POST['seotitle'] : '';
        $data['keywords'] = input('post.keywords', '', 'strip_tags');
        $data['description'] = input('post.description', '', 'strip_tags');
        $data['content'] = isset($_POST['content']) ? $_POST['content'] : false;
        $data['thumbnail'] = input('post.thumbnail', '', 'strip_tags');
        $data['o'] = input('post.o', '', 'strip_tags');
        $data['t'] = isset($_POST['t']) ? strtotime($_POST['t']) : 0;
        //$data['t'] = time();
        if (!$data['sid'] or !$data['title'] or !$data['content']) {
           // $this->error('警告！文章分类、文章标题及文章内容为必填项目。');
        }
        if ($aid) {
			//print_r($sid);die;
			$list = db('category')->where('pid',$sid)->find();
			if($list){
				$this->error('本栏目下有子栏目，请选择子栏目！',null,null,1)	;
			}
            db('article')->data($data)->where('aid',$aid)->update();
            addlog('编辑文章，AID：' . $aid);
            $this->success('恭喜！文章编辑成功！',url('index',array('pid'=>$pid)),null,1);
			//return json(array('code' => 200, 'msg' => '恭喜！文章编辑成功！' , 'pid'=>''));
        } else {
			$list = db('category')->where('pid',$sid)->find();
			if($list){
				$this->error('本栏目下有子栏目，请选择子栏目！',null,null,1);
			}
            $aid = db('article')->data($data)->insert();
            if ($aid) {
                addlog('新增文章，AID：' . $aid);
                $this->success('恭喜！文章新增成功！',url('index',array('pid'=>$pid)),null,1);
            } else {
                $this->error('抱歉，未知错误！');
            }

        }
		 
	
	}
	
	
	
	
}
